package main.leetcode.clockin.June;

import java.util.ArrayList;
import java.util.List;

/**
 * 面试题29. 顺时针打印矩阵
 *
 * <p>输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 *
 * <p>示例 1：输入：matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出：[1,2,3,6,9,8,7,4,5]
 *
 * <p>示例 2：输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 *
 * <p>限制：0 <= matrix.length <= 100 0 <= matrix[i].length <= 100
 */
public class day5 {
    public static void main(String[] args) {
        System.out.println(new day5().spiralOrder(new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}));
        System.out.println(
                new day5()
                        .spiralOrder(
                                new int[][] {
                                    {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}
                                }));
        System.out.println(
                new day5().spiralOrder(new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}));
        System.out.println(new day5().spiralOrder(new int[][] {{6, 9, 7}}));
        System.out.println(new day5().spiralOrder(new int[][] {{6}, {9}, {7}}));
    }

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return res;
        }
        int m = matrix.length;
        int n = matrix[0].length;
        int up = 0, down = m - 1, left = 0, right = n - 1;
        while (true) {
            for (int j = left; j <= right; ++j) {
                res.add(matrix[up][j]);
            }
            if (++up > down) break;

            for (int i = up; i <= down; ++i) {
                res.add(matrix[i][right]);
            }
            if (--right < left) break;

            for (int j = right; j >= left; --j) {
                res.add(matrix[down][j]);
            }
            if (--down < up) break;

            for (int i = down; i >= up; --i) {
                res.add(matrix[i][left]);
            }
            if (++left > right) break;
        }
        return res;
    }
}
